/**
 * Copyright 2008-2009. Chongqing Communications Industry Services Co.,Ltd Information Technology Branch. All rights
 * reserved. <a>http://www.cqcis.com</a>
 */
package com.cq.bd.dwr;

import com.cq.bd.BDException;
import com.cq.bd.base.BaseDwr;
import com.cq.bd.dto.ChgPwdResult;
import com.cq.bd.dto.LoginResult;
import com.cq.bd.security.UserDetails;
import com.cq.bd.service.LoginService;
import com.cq.bd.utils.AuthenticationHelper;

/**
 * 登陆
 * 
 * @author huangmy
 * @date   2009-10-3
 */
public class LoginDwr extends BaseDwr {
    private static final long serialVersionUID = 1L;
    private LoginService loginService;

    /**
     * 登陆
     * 
     * @param loginCode
     * @param password
     * @return
     */
    public LoginResult login(String loginCode, String password) {
        return this.loginService.doLogin(loginCode, password);
    }
    
    /**
     * 当前session中的用户，如果session为空，返回null
     * 
     * @return
     */
    public UserDetails getSessionUser() {
        return (UserDetails) AuthenticationHelper.getUser();
    }
    
    /**
     * 修改密码
     * 
     * @param oldPwd
     * @param newPwd
     * @return 成功返回1， 否则返回2
     */
    public ChgPwdResult changePwd(String oldPwd, String newPwd) {
        ChgPwdResult result = null;
        
        try {
            UserDetails ud = (UserDetails)AuthenticationHelper.getUser();
            if (ud == null) {
                throw new BDException("session超时，请重新登录！");
            }
            result = this.loginService.doChangePassword(ud.getLoginId(), oldPwd, newPwd);
        } catch (Exception e) {
            result = new ChgPwdResult();
            result.setMessage(e.getMessage());
        }
        
        return result != null ? result : new ChgPwdResult();
    }
    
    /**
     * 退出登录
     * 
     */
    public void logOut() {
        try {
            UserDetails ud = (UserDetails) AuthenticationHelper.getUser();
            if (ud != null) {
                this.loginService.doLoginOut(ud);
            }
        } finally {
            AuthenticationHelper.loginOut();
            AuthenticationHelper.removeUser();
        }
    }

    public void setLoginService(LoginService loginService) {
        this.loginService = loginService;
    }
}
